package leunghan.editor.cn.sort;

import java.util.Arrays;

/**
 * @author Leunghan
 * @date 2025/2/20 23:42
 */
public class Code_02_SelectionSort {
    public static void selectionSort(int[] arr) {
        if (arr == null || arr.length < 2) {
            return;
        }

        for (int i = 0; i < arr.length - 1; i++) {
            int minIndex = i;
            for (int j = i + 1; j < arr.length; j++) {
                minIndex = arr[minIndex] < arr[j] ? minIndex : j;
            }
            swap(arr, minIndex, i);
        }
    }

    public static void swap(int[] arr, int i, int j) {
        int tmp = arr[i];
        arr[i] = arr[j];
        arr[j] = tmp;
    }

    public static int[] copyArray(int[] arr) {
        if (arr == null) {
            return null;
        }

        int[] res = new int[arr.length];
        for (int i = 0; i < arr.length; i++) {
            res[i] = arr[i];
        }
        return res;
    }


    public static int[] generateRandomArray(int maxSize, int maxValue) {
        int[] res = new int[(int) ((maxSize + 1) * Math.random())];

        for (int i = 0; i < res.length; i++) {
            res[i] = (int) ((maxValue + 1) * Math.random()) - (int) ((maxValue) * Math.random());
        }

        return res;
    }

    public static boolean isEqual(int[] arr1, int[] arr2) {
        if (arr1 == null && arr2 == null) {
            return true;
        }
        if (arr1 == null || arr2 == null) {
            return false;
        }
        if (arr1.length != arr2.length) {
            return false;
        }

        for (int i = 0; i < arr1.length; i++) {
            if (arr1[i] != arr2[i]) {
                return false;
            }
        }

        return true;
    }

    public static void main(String[] args) {
        int[] arr1 = generateRandomArray(10, 100);
        int[] arr2 = copyArray(arr1);

        selectionSort(arr1);
        Arrays.sort(arr2);

        System.out.println(isEqual(arr1, arr2));
    }
}
